<template>
  <div v-loading="loading">
    <div style="width: 80px;height: 30px; ">
      <input type="checkbox" v-model="checkedAll" @change="checkAll" style="width: 20px;height: 20px;float: left;opacity: 1;">
      <span style="float: right;margin-left: 20px;margin-top: -5px;font-size: 20px; ">全选</span>
    </div>
    <div v-for="(item) in prolist" :key="item.id" class="w-90p mt-5 pd-5 p-r" v-if="item.orderDetailVOS && item.orderDetailVOS.length">
      <div class="tags-box">
        <el-tag v-if="item.submitComplainAppeal" class="mr-5" color="#fdfabd" type="warning">已提交投诉</el-tag>
        <el-tag class="mr-5" v-if="item.refundMark" type="danger">{{item.refundMark}}</el-tag>
        <el-tag v-if="item.staffForward" type="danger">{{item.staffForward}}</el-tag>

        <el-button v-if="canToconfirm(item)" type="primary" size="mini" @click="toUnconfirm(item)">退回未确认状态</el-button>
      </div>
      <!-- 生产订单操作列表在这里面的div进行样式的改变与块级的修改 -->
      <div v-for="(detail,key) in item.orderDetailVOS" :key="key" style="display: flex;" :class="detail.printingTimes > 0 ? 'deliveryBackground':'deliveryStartTime'" class="prodution-item">
        <div sytle="padding-top: 10px;padding-left: 5px;">
          <input type="checkbox"
            v-model="detail.checked"
            :data-warehouseId="item.warehouseId"
            @change="handleCheck(detail,key,item,$event)"
            style="width: 20px;height: 20px;float: left;opacity: 1;"
          />
        </div>
        <el-col style="position: relative;">
          <el-col style="display: flex;align-items: center;">
            <div ref="print" style="margin-left: 10px; font-size: 16px !important;width: 80%;">
              <div class="mtb-15">
                <span class="fz-18 fw-bold">{{ detail.goodsName }}</span>
                <span class="ml-10 fw-bold" style="color: #F56C6C;">({{ detail.goodsSpecs }})</span>
                <el-tooltip effect="dark" content="请优先处理三方订单" placement="top" v-if="firstChannelList.includes(detail.channelName)">
                  <span class="fire-box" type="danger">
                    <img class="fire-icon" src="@/assets/image/icon_fire.png" alt="" srcset="" :style="{'width': '24px'}">
                    <span class="fw-bold fz-14 ml-5">三方 - {{ detail.channelName }}</span>
                  </span>
                </el-tooltip>
              </div>
              <h2 v-if="(detail.num > 1 ? true : false) && (detail.goodsTypeName == '蛋糕' ? true : false)" style="color: red;">数量：{{ detail.num }}个</h2>
              <!-- <h3 style="display: flex; align-items: center; height: 0; font-size: 18px;">规格：</h3> -->
              <div style="display: flex; align-items: center;justify-content: space-between; margin-bottom: 5px;">
                <p class = 'blessing' >祝福语：
                  <el-tooltip v-if="detail.blessings" placement="top" :content="detail.blessings">
                    <span style=" color: #F56C6C; font-weight: bold;display: block;width: 80%;">{{ detail.blessings }}</span>
                  </el-tooltip>
                </p>
                <p class = 'blessing' >客户备注：
                  <el-tooltip v-if="item.customerNotes" placement="top" :content="item.customerNotes">
                    <span style="color: #F56C6C; font-weight: bold;display: block;width: 80%;">{{ item.customerNotes }}</span>
                  </el-tooltip>
                </p>
              </div>
              <div style="display: flex; align-items: center;justify-content: space-between; margin-bottom: 5px;">
                <p class = 'blessing' >生产需求：
                  <el-tooltip v-if="item.productionNotes" placement="top" :content="item.productionNotes">
                    <span style="color: #F56C6C; font-weight: bold;display: block;width: 80%;">{{ item.productionNotes }}</span>
                  </el-tooltip>
                </p>
              </div>
              <p style = 'width: 100%; margin: 0'>
                <span>配送时间：{{ item.deliveryStartTime.slice(5,16) }}~{{ item.deliveryEndTime.slice(11,16) }}</span>
                <span style="margin-left: 20px;">下单时间：{{ item.orderTime.slice(5,25) }}</span>
                <span style="margin-left: 20px;">分仓：{{ item.branchWarehouse }}</span>
                <span style="margin-left: 20px;" >单号：{{item.xmbzNo}}</span>
                <!-- <span style="margin-left: 20px;" >是否跳舞：{{danceLabelMap[item.isDance] || '-'}}</span> -->
              </p>
              <p class="d-if ai-c"><barcode
                tag="img"
                :value="detail.id"
                :options="{
                      height: 22,
                      width: 1,
                      displayValue: false,
                      margin: 1,
                    }"
                style="margin-top: 2px"
              ></barcode>
              <el-button icon="el-icon-search" class="ml-10" type="primary" size="mini" @click="viewDetail(detail)">查看详情</el-button>
            </p>
            </div>
            <!-- <span v-if="item.refundMark === '平台退款中' ? true : false" class="timecolor">平台退款中</span> -->
            <div class="operation-box mt-40">
                <el-button type="primary" v-if="detail.productionState==3?true:false" size="small" @click="productionGoodsRollback(detail.id)" class="production-button production-kindbutton">退回待生产</el-button>
                <el-button type="primary" :data-id="detail.orderId" :data-orderDetailId="detail.id" v-if="detail.productionState==2?true:false" size="small" @click="startProdution($event)" class="production-button production-kindbutton">开始生产</el-button>
                <el-button type="primary" :data-id="detail.orderId" :data-orderDetailId="detail.id" v-if="detail.productionState==3?true:false" size="small" @click="putInStorage($event)" class="production-button production-kindbutton" style='margin-right: 10px'>入库</el-button>
                <el-button type="primary" :disabled="StampStoragebtn == true?true:false" size="small" v-if="detail.productionState==3 || detail.productionState==4 || detail.productionState==5" class="production-button production-kindbutton" @click="StampStorage($event,detail)" data-btn-type="print">
                  打印
                  <span v-if="detail.printingTimes !== undefined && detail.printingTimes !== 0 && detail.printingTimes !== '' && detail.printingTimes <= 99">
                    ：{{ detail.printingTimes }}次
                  </span>
                  <span v-if="detail.printingTimes !== undefined && detail.printingTimes !== 0 && detail.printingTimes !== '' && detail.printingTimes > 99">
                    ：99+次
                  </span>
                </el-button>
                <el-button type="primary" size="small" v-if="detail.productionState==3 || detail.productionState==4 ? true:false" class="production-button production-kindbutton" @click="GetIngredients(detail, item)" data-btn-type="print">
                  打印配料表
                </el-button>
            </div>
            <div class="production-status" :style="getStatusStyle(detail)">{{ detail.productionStateName }}</div>
          </el-col>
          <!-- <el-col :span="22" :class="detail.printingTimes > 0  ? 'deliveryBackground':'deliveryStartTime'" style="margin-left: 20px;">
            <div v-show="(index == showIndex) && ((clickNumber % 2) == 1 ) ? true : false" :class="detail.printingTimes > 0 ? 'deliveryBackground':'deliveryStartTime'" style="display: flex;justify-content: space-between;margin-right: 35px;font-size: 15px;">
              <span>制作人：{{ detail.producer }}</span>
              <span>裱花人：{{ detail.carver }}</span>
              <span>打包人：{{ detail.packer }}</span>
            </div>
          </el-col> -->
          <!-- <div style="width: 760px;margin-left: 18px;border-bottom: 1px dashed #cecece;"></div> -->
          <div>
          </div>
        </el-col>
      </div>
    </div>
    <div style="position: fixed;top: -100%;right: -100%;">
      <ingredientBox ref="ingredientBox"></ingredientBox>
    </div>
    <el-pagination
      background
      :current-page.sync="currentPage"
      layout="prev, pager, next, sizes, total"
      :page-sizes="[5, 10, 15, 20]"
      :page-size.sync="pagesize"
      :total="prolisttotal"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
      style="margin-bottom: 30px;"
    >
    </el-pagination>
    <el-dialog :visible.sync="productionFlag" center :append-to-body="true" :lock-scroll="false" width="40%" z-index="2007">
      <div style="width: 100%;height: 350px;">
        <el-scrollbar class="page-component__scroll" style="height: 400px;">
          <div v-if="productionStartFlag">
            <el-col style="margin-top: 1%;">
              <div class="order-message" style="height: 35px;">
                <el-col style="padding-left: 5px;font-size: 20px;">
                  开始生产
                </el-col>
              </div>
              <div style="height: 300px;margin-left: 25px;">
                <el-form :model="startruleForm" :rules="startrules" ref="startruleForm" label-width="100px" class="demo-ruleForm">
                  <el-form-item label="制作人" prop="producer">
                    <el-input
                      v-model="startruleForm.producer"
                      placeholder="请输入制作人"
                      maxlength="10"
                      style="width: 300px;"
                    ></el-input>
                  </el-form-item>
                  <el-form-item label="裱花人" prop="carver">
                    <el-input
                      v-model="startruleForm.carver"
                      placeholder="请输入裱花人"
                      maxlength="10"
                      style="width: 300px;"
                    ></el-input>
                  </el-form-item>
                  <el-form-item label="打包人" prop="packer">
                    <el-input
                      v-model="startruleForm.packer"
                      placeholder="请输入打包人"
                      maxlength="10"
                      style="width: 300px;"
                    ></el-input>
                  </el-form-item>
                  <el-form-item>
                    <el-button @click="startResetForm('startruleForm')">取消</el-button>
                    <el-button type="primary" @click="startSubmitForm('startruleForm')">确定</el-button>
                  </el-form-item>
                </el-form>
              </div>
            </el-col>
          </div>
        </el-scrollbar>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="StorageStartFlag" center :append-to-body="true" :lock-scroll="false" width="30%" z-index="2007">
      <div style="width: 100%;height: 100px;">
        <div style="width: 100%;">
          <el-form :model="StorageruleForm" ref="StorageruleForm" label-width="100px" class="demo-ruleForm">
            <div style="font-size: 17px;margin-left: 5px;">
              是否执行入库操作？
            </div>
            <el-form-item style="margin-top: 7%;display: flex;justify-content: flex-end;">
              <el-button @click="StorageResetForm()">取消</el-button>
              <el-button type="primary" @click="StorageSubmitForm('StorageruleForm')">确定</el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="IngredientsFlag" :close-on-click-modal="false" center :append-to-body="true" :lock-scroll="false" width="50%" z-index="2007">
      <div style="width: 100%;height: 300px;">
        <div style="width: 100%;">
          <el-form :model="IngredientsForm" ref="IngredientsForm" :rules="Ingredientsrules" label-width="100px" class="demo-ruleForm">
            <div style="font-size: 17px;margin-left: 5px;margin-bottom: 50px;">
              上传配料表
            </div>
            <el-form-item label="搜索蛋糕" style="margin-left: 30px;" prop="Ingredientgoods">
              <el-cascader
                ref="cascaderRef"
                :key="isResouceShow"
                v-model="IngredientsForm.Ingredientgoods"
                placeholder="蛋糕"
                :options="GoodsByNameList.length > 0 ? GoodsByNameList : GoodsByNameLists"
                :props="{ expandTrigger: 'hover' }"
                @input.native="getName($event)"
                @change="handleChange"
                filterable
              ></el-cascader>
            </el-form-item>
            <el-form-item style="display: flex;justify-content: space-around;margin-top: 130px;margin-right: 70px;">
              <el-button @click="IngredientsResetForm('IngredientsForm')" style="margin-right: 50px;">取消</el-button>
              <el-button type="primary" @click="IngredientsSubmitForm('IngredientsForm')">确定</el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </el-dialog>
    <!-- 打印 -->
    <detailDialog ref="detailDialog"></detailDialog>
  </div>
</template>
<script language="javascript" type="text/javascript" src="../lodop/LodopFuncs.js"></script>

<script>

//  生产管理 操作管理 修改样式 修改位置

// import {
//   citySelect,
// } from "@/api/createOrder";
// import Pagination from "@/components/Pagination"; // 分页
// import Print from '@/plugs/print.js';
// Vue.use(Print); // 注册
// import vueEasyPrint from "vue-easy-print";
import VueBarcode from "@xkeshi/vue-barcode";

import {
  singleStartProduction, //开始生产
  getProductionQueryPage, //查询列表
  orderWarehousing, // 入库和批量入库
  confirmAbnormalLog, // 确认入库记录
  addOrderWarehousingLog, // 新增入库记录
  // getOrderWarehousingLogList, // 获取入库记录
  getMaterielGoodsByName,// 根据物料商品名称模糊查询
  getMaterielGoodsPrintingInfo,// 搜索出物料商品,打印需要返回的信息
  getShortOrderDetail,//订单明细
  productionGoodsRollbackApi,//退回生产中
  backStatus,
  orderPrinting, // 批量打印
} from '@/api/shop'
import ingredientBox from "@/views/scheduling/index/cake/components/printForm/ingredientBox"; // 打印曲奇模板
import { danceLabelMap, statusColorMap } from '@/const'
import detailDialog from './detailDialog'

// 优先渠道
const firstChannelList = ['美团外卖', '美团团购', '饿了么', '抖音'];

export default {
  components: { barcode: VueBarcode, ingredientBox, detailDialog },
  props: {
    submitForm: {
      type: Function,
      default: null
    },
    productionQuery: {
      required: true
    },
    labelcheckedFlag: {
      required: false
    },
    productionInfoChecked: {
      required: false
    },
    isOpenPrintPreview: {
      required: false
    },
    getMainWarehouseList: {
      default: () => []
    },
  },
  data() {
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入制作人'));
      } else {
        this.startruleForm.producer = value.replace(/\s+/g, '');
        callback();
      }
    };
    var validatePass1 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入裱花人'));
      } else {
        this.startruleForm.carver = value.replace(/\s+/g, '');
        callback();
      }
    };
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入打包人'));
      } else {
        this.startruleForm.packer = value.replace(/\s+/g, '');
        callback();
      }
    };

    const cityId = JSON.parse(window.localStorage.getItem("saber-areaId")).content
    return {
      firstChannelList,
      prolisttotal: 0,
      total: 0,
      pagesize: 10,
      currentPage: 1,
      checkedAll: false,
      prolist: '',
      productionFlag: false, // 开始生产弹窗Flag
      productionStartFlag: false, // 开始生产按钮请求列表弹窗显示Flag
      StorageStartFlag: false, // 入库按钮请求列表弹窗显示Flag
      startruleForm: { // 开始生产
        orderId: 2, // 后台单号
        orderDetailId: 2, // 订单明细id
        producer: '', // 制作人
        carver: '', // 裱花人
        packer: '', // 打包人
      },
      startrules: {
        producer: [
          {
            required: true,
            validator: validatePass,
            trigger: 'change'
          }
        ],
        carver: [
          { required: true,
            validator: validatePass1,
            // message: '请输入裱花人',
            trigger: 'change'
          }
        ],
        packer: [
          { required: true,
            validator: validatePass2,
            // message: '请输入打包人',
            trigger: 'change'
          }
        ]
      },
      StorageruleForm: { // 入库
        orderId: 132,
        orderDetailId: 132
      },
      // StorageRecordStartFlag: false, // 入库成功与否弹框
      StorageRecordList: [], // 获取入库记录列表
      loading: false, // loading加载
      addOrderWarehousingLog: { // 新增入库记录列表
        orderId: 123,
        orderDetailId: 132,
        warehousingState: 0
      },
      showIndex: '', // 折叠面板索引
      clickNumber: '', // 折叠面板点击次数
      StampStoragebtn: false,
      CookieTemplateList: [],// 配料表
      IngredientsFlag: false,// 配料表是否上传弹框
      IngredientsForm: {
        deptId: cityId,
        Ingredientgoods: [],
        name: '',
        page: 1,
        size: 10,
      },
      Ingredientsrules: {
        Ingredientgoods: [{ required: true, message: '请选择蛋糕', trigger: 'change' }]
      },
      GoodsByNameList: [],
      GoodsByNameLists: [{
        value: '111',
        label: '无匹配数据',
        disabled: true
      }],
      isResouceShow: 1,
      danceLabelMap,
    };
  },
  mounted() {
    let code = "";
    let lastTime, nextTime
    let lastCode, nextCode
    let that = this
    window.parseCode = function(code){
      that.parseCode(code)
    }
    this.changeCurrentPage()
    window.document.onkeypress = function (e) {
      if (window.event) { // IE
        nextCode = e.keyCode
      } else if (e.which) { // Netscape/Firefox/Opera
        nextCode = e.which
      }
      if (e.which === 13) {
        if (code.length < 3) return // 手动输入的时间不会让code的长度大于2，所以这里只会对扫码枪有
        that.parseCode(code) // 获取到扫码枪输入的内容，做别的操作
        code = ''
        lastCode = ''
        lastTime = ''
        return
      }
      nextTime = new Date().getTime()
      if (!lastTime && !lastCode) {
        // console.log('扫码开始。。。')
        code += e.key
      }
      if (lastCode && lastTime && nextTime - lastTime > 500) { // 当扫码前有keypress事件时,防止首字缺失
        // console.log('防止首字缺失。。。')
        code = e.key
      } else if (lastCode && lastTime) {
        // console.log('扫码中。。。')
        code += e.key
      }
      lastCode = nextCode
      lastTime = nextTime
    }
    setTimeout(() => {
      this.getList()
    },800)
  },
  watch: {
    'IngredientsFlag'() {
      if(!this.IngredientsFlag) {
        this.GoodsByNameList = [];// 配料表搜索数据列表清空
        this.CookieTemplateList = '';// 打印数据
      }
    }
  },
  methods: {
    // 修改下坐标长度
    changeCurrentPage(e){
    this.currentPage = 1
     window.addEventListener('keydown', (e)=>{
        if(e.keyCode == 13 ){
          this.currentPage = 1
        }
      })
    },
    getMainWarehouse() {
      const select = this.getMainWarehouseList.find(item => {
        return item.id === this.productionQuery.mainWarehouse
      })
      return select
    },
    getOrderListParams() {
      const mainWarehouse = this.getMainWarehouse()
      const params = {
        deptId: this.productionQuery.deptId,
        xmbzNo: this.productionQuery.xmbzNo,
        mainWarehouse:mainWarehouse.deptName === '全部' ? '' : mainWarehouse.deptName,
        warehouseId: this.productionQuery.warehouseId,
        status: this.productionQuery.status,
        deliveryStartTime: this.productionQuery.deliveryStartTime,
        deliveryEndTime: this.productionQuery.deliveryEndTime,
        goodsName: this.productionQuery.goodsName,
        goodsSpecs: this.productionQuery.goodsSpecs,
        printingState: this.productionQuery.printingState,
        page: this.productionQuery.page,
        size: this.productionQuery.size
      }
      return params
    },
    getList() {
      const params = this.getOrderListParams()
      getProductionQueryPage(params).then(res => {
        this.prolisttotal = res.data.data.total;
        this.prolist = res.data.data.rows;
        const details = []
        this.prolist.forEach(itemorder => {
          itemorder.getHour = this.getHour(itemorder.deliveryEndTime).toFixed(2);
          if (itemorder.getHour > 3) {
            itemorder.getHour = true
          } else if (itemorder.getHour < 3) {
            itemorder.getHour = false
          } else if (itemorder.getHour.toString() === 'NaN') {
            itemorder.getHour = true
          }
          itemorder.orderDetailVOS.forEach(item => {
            item.warehouseId = itemorder.warehouseId
            item.isDance = itemorder.isDance
            this.$set(item, "checked", false)
            details.push(item)
          })
        })
        this.checkedAll = false
      })
    },
    // 计算时间差
    getHour(endTime) {
      let nowYear = new Date().getFullYear();
      let nowMonth = (new Date().getMonth() + 1) < 10 ? "0" + (new Date().getMonth() + 1) : (new Date().getMonth() +
        1);
      let nowDate = new Date().getDate() < 10 ? "0" + new Date().getDate() : new Date().getDate();
      let nowHours = new Date().getHours() < 10 ? "0" + new Date().getHours() : new Date().getHours();
      let nowMinutes = new Date().getMinutes() < 10 ? "0" + new Date().getMinutes() : new Date().getMinutes();
      // console.log(e.currentTarget.dataset.time,nowYear + '-' + nowMonth + '-' + nowDate + ' ' + nowHours + ':' + nowMinutes)
      let nowTime = nowYear + '-' + nowMonth + '-' + nowDate + ' ' + nowHours + ':' + nowMinutes
      let s1 = new Date(endTime.replace(/-/g, '/'));
      // console.log('s1',s1)
      let s2 = new Date(nowTime.replace(/-/g, '/'));
      let ms = Math.abs(s1.getTime() - s2.getTime());
      let getHour = ms / 1000 / 60 / 60;
      // console.log('getHour',getHour)
      return getHour
    },
    // 初始页currentPage、初始每页数据数pagesize和数据data
    handleSizeChange: function (size) {
      this.currentPage = 1
      this.pagesize = size;
      this.productionQuery.page = this.currentPage
      this.productionQuery.size = this.pagesize
      this.getList()
    },
    // 跳转currentPage 02
    handleCurrentChange: function(currentPage) {
      this.currentPage = currentPage
      this.productionQuery.page = currentPage
      this.productionQuery.size = this.pagesize
      this.getList()
      document.body.scrollTop = document.documentElement.scrollTop = 0;
    },
    //全选
    checkAll() {
      const details = [];
      this.prolist.forEach(itemorder => {
        itemorder.orderDetailVOS.forEach(item => {
          item.checked = this.checkedAll
          details.push(item)
        })
      })
    },
    handleCheck(detail,key,item,e) { //反选
      var check = this.getChecked();
      if (check.indexOf(false) == -1) {
        this.checkedAll = true;
      } else {
        this.checkedAll = false;
      }
    },
    getChecked() {
      const checkedList = []
      this.prolist.forEach(itemorder => {
        itemorder.orderDetailVOS.forEach(item => {
          item.checked && checkedList.push(item)
        })
      })
      return checkedList
    },
    startProdution(e) { // 开始生产 02
      // console.log(e.currentTarget.dataset)
      this.startruleForm.orderId = e.currentTarget.dataset.id
      this.startruleForm.orderDetailId = e.currentTarget.dataset.orderdetailid
      this.startruleForm.producer = '未填写' // 制作人
      this.startruleForm.carver = '未填写' // 裱花人
      this.startruleForm.packer = '未填写' // 打包人
      singleStartProduction(this.startruleForm).then(res => {
        if(res.data.code == 200) {
          this.$notify({
            title: '生产成功',
            message: '请您耐心等待',
            type: 'success'
          })
          this.$emit('getProductionNumber')
          // this.checkAll()
          setTimeout(() => {
            this.productionFlag = false
            this.productionStartFlag = false
          }, 1*1000);
          this.getList();
        }
      })
      // this.productionFlag = true
      // this.productionStartFlag = true
    },
    /**退回生产中*/
    productionGoodsRollback(detailId) {
      this.$confirm('确认退回待生产吗？')
        .then(() => {
          productionGoodsRollbackApi({detailId: detailId}).then(res => {
            if(res.data.code == 200) {
              this.$emit('getProductionNumber')
              this.getList();
              this.$notify({
                title: '退回待生产成功',
                message: '请您耐心等待',
                type: 'success'
              })
            }
          })
        })
        .catch(() => {});
    },
    startSubmitForm(formName) {// 开始生产确认按钮
      this.$refs[formName].validate((valid) => {
        if (valid) {
          singleStartProduction(this.startruleForm).then(res => {
            if(res.data.code == 200) {
              this.$notify({
                title: '生产成功',
                message: '请您耐心等待',
                type: 'success'
              })
              this.$refs[formName].resetFields();
              this.$emit('getProductionNumber')
              setTimeout(() => {
                this.productionFlag = false
                this.productionStartFlag = false
              }, 1*1000);
            }
          })
        } else {
          return false;
        }
      })
    },
    startResetForm(formName) {// 开始生产取消按钮
      this.$refs[formName].resetFields();
      this.productionFlag = false
      this.productionStartFlag = false
      // this.complainFlag = false;
    },
    putInStorage(e) { // 入库
      this.StorageStartFlag = true
      this.StorageruleForm.orderId = e.currentTarget.dataset.id
      this.StorageruleForm.orderDetailId= e.currentTarget.dataset.orderdetailid
      let Storagelist = []
      Storagelist.push(Number(e.currentTarget.dataset.orderdetailid))
      this.StorageRecordList = Storagelist
      // this.StorageruleForm.orderDetailId = Number(e.currentTarget.dataset.orderdetailid)
    },
    StorageSubmitForm(formName) {// 入库确认按钮
      this.$refs[formName].validate((valid) => {
        if (valid) {
          orderWarehousing(this.StorageruleForm).then(res => {
            if(res.data.code == 200) {
              this.$notify({
                title: '入库成功',
                message: '请您耐心等待',
                type: 'success'
              })
              this.$refs[formName].resetFields();
              this.$emit('getProductionNumber')
              this.StorageStartFlag = false;
              this.getList();
            }
          })
        } else {
          alert('0000000000000')
          return false;
        }
      });
    },
    StorageResetForm() {// 入库取消按钮
      this.StorageStartFlag = false
    },
    StampStorage(e, item) { // 打印
      if(item.nutrients != 1 && this.productionInfoChecked){
        this.$confirm('该商品尚未上传物料表', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          center: true,
          closeOnClickModal: false,// 是否可通过点击遮罩关闭
          showClose: false,
        }).then(() => {
          // this.getGoodsByNameList();
        }).catch(() => {
        });
      }else{
        window.localStorage.setItem('proPathFlag',this.$route.path);
        this.$emit('onPrint', [item])
      }
    },
    // 创建扫描控件
    parseCode (code) {
      const Numarr = [];
      let Numobj = `${code}`;
      Numobj = JSON.parse(Numobj);
      let _self = this;
      function execute(Numobj) {
        _self.StorageruleForm.orderId = Numobj.orderId; // 入库请求参数
        _self.StorageruleForm.orderDetailId= Numobj.orderDetailId;  // 入库请求参数
        // 新增入库记录
        _self.addOrderWarehousingLog.orderId = Numobj.orderId;
        _self.addOrderWarehousingLog.orderDetailId= Numobj.orderDetailId;
        // 获取入库记录请求列表
        let Storagelist = [];
        Storagelist.push(Numobj.orderDetailId);
        _self.StorageRecordList = Storagelist;
        // 确认入库请求参数
        Numarr.push(Numobj.orderId,Numobj.orderDetailId);
        if(Numobj.status === 2 || Numobj.status === 4 || Numobj.status === 9 || Numobj.status === 10) {
          let msg = '';
          if(Numobj.status == 4) {
            msg = '请勿重复入库!';
          }else if(Numobj.status == 9) {
            msg = '蛋糕已改期';
          }else if(Numobj.status == 10) {
            msg = '蛋糕已退订';
          }else if(Numobj.status == 2) {
            msg = '蛋糕暂未制作完成';
          }
          _self.$message({
            type: 'warning',
            message: msg
          });
          return;
        }
        orderWarehousing(_self.StorageruleForm).then(res => {
          if(res.data.code == 200) {
            // console.log(' 请求入库')
            _self.addOrderWarehousingLog.warehousingState = 1
            // 新增入库记录
            addOrderWarehousingLog(_self.addOrderWarehousingLog).then(res => {
              if(res.data.code == 200) {
                _self.$notify({
                  title: '入库成功',
                  message: '请您耐心等待',
                  type: 'success'
                });
                _self.$emit('getProductionNumber');
                _self.getList();
              }
            })
          } else if(res.data.code == 301) { // 二维码信息不存在
            _self.$notify({
              title: '二维码信息不存在',
              message: '请确认二维码信息',
              type: 'warning'
            });
            _self.getList();
          }
        }).catch(err => {
          console.log('err01',err)
        })
      }
      if(Numobj.orderId === undefined || Numobj.orderId === null){
        //条形码
        getShortOrderDetail({detailId: Numobj}).then(res=>{
          execute(res.data.data)
        })
      } else {
        //二维码
        execute(Numobj)
      }

    },
    // 打印配料表
    GetIngredients(detail, item) {
      this.IngredientsForm.orderId = detail.orderId;//搜索出物料商品,打印需要返回的信息orderId
      if(detail.nutrients != 1) {
        this.$confirm('该商品尚未上传物料表', '提示', {
          confirmButtonText: '去上传',
          cancelButtonText: '取消',
          type: 'warning',
          center: true,
          closeOnClickModal: false,// 是否可通过点击遮罩关闭
          showClose: false,
        }).then(() => {
          this.IngredientsFlag = true;
          // this.getGoodsByNameList();
        })
      } else {
        orderPrinting([detail.id]).then(res => {
          const orderData = res.data.data && res.data.data[0]
          if (orderData) {
            window.localStorage.setItem('proPathFlag',this.$route.path);
            this.selIngredientOrder = item
            let goodsSkuProduction = orderData.goodsSkuProduction;
            this.CookieTemplateList = goodsSkuProduction;
            this.CookieTemplateList.orderDetail = item;
            this.$refs.ingredientBox.print({dataList: [this.CookieTemplateList], isPreview: this.isOpenPrintPreview})
          }
        })
        // console.log('this.CookieTemplateList',this.CookieTemplateList)
      }
    },
    // 取消上传配料表
    IngredientsResetForm(formName) {
      this.$refs[formName].resetFields();
      this.IngredientsFlag = false;
    },
    IngredientsSubmitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if(valid) {
          getMaterielGoodsPrintingInfo(this.IngredientsForm).then(res => {
            let result = JSON.stringify(res.data.data);
            if( result == '{}') {
              this.IngredientsFlag = true;
              this.$message.warning('该商品没有有物料表！');
            } else {
              this.CookieTemplateList = res.data.data;
              this.CookieTemplateList.orderDetail = this.selIngredientOrder;
              this.$refs.ingredientBox.print({dataList: [this.CookieTemplateList], isPreview: this.isOpenPrintPreview})
              this.$refs[formName].resetFields();
            }
          })
        } else {
          return false;
        }
      })
    },
    // 根据物料商品名称模糊查询
    getGoodsByNameList(e) {
      getMaterielGoodsByName(this.IngredientsForm).then(res => {
        res.data.data.rows.forEach(item => {
          item.value = item.id;
          item.label = item.name;
          item.children = item.goodsSkuVOS;
          if(item.children.length > 0) {
            item.children.forEach(childitem => {
              childitem.value = childitem.id;
              childitem.label = childitem.specs;
            })
          }
        })
        if(this.IngredientsForm.name == '') {
          this.GoodsByNameList = [];
        } else {
          this.GoodsByNameList = res.data.data.rows;
        }
      })
    },
    getName(e) {
      // console.log('console.log()',e.target.value);
      this.IngredientsForm.name = e.target.value;
      this.getGoodsByNameList();
    },
    handleChange(value) {
      // console.log(value);
      if(this.IngredientsForm.Ingredientgoods.length > 0 ) {
        this.IngredientsForm.skuId = this.IngredientsForm.Ingredientgoods[1];
      }
    },
    toUnconfirm(order) {
      this.$confirm('是否退回未确认状态？')
        .then(() => {
          backStatus([order.id]).then(res => {
            if(res.data.code == 200) {
              this.$emit('getProductionNumber')
              this.getList();
              this.$notify({
                title: '提示',
                message: '退回未确认成功',
                type: 'success'
              })
            }
          })
        })
        .catch(() => {});
    },
    canToconfirm(order) {
      return order.orderDetailVOS.every(item => item.productionState == 2) && false
    },
    getStatusStyle(detail) {
      return {
        'border-color': statusColorMap[detail.productionState],
        'color': statusColorMap[detail.productionState],
      }
    },
    viewDetail(data) {
      this.$refs.detailDialog.show({data})
    }
  },
  beforeDestroy() {
    window.document.onkeypress = null
  }
}
</script>

<style lang="scss" scoped>
h1,
h2 {
  font-weight: normal;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
.prodution-item {
  padding: 10px;
}
.tags-box {
  position: absolute;
  right: 20px;
  top: 20px;
  z-index: 1;
  .el-tag {
    background-color: #fef0f0;
  }
}
.operation-box {
  .el-button {
    display: block;
    margin: 5px 0 0 0;
  }
}
.checked {
  width: 20px;
  height: 20px;
}
</style>

<style >
.blessing{
    display: flex;
    margin: 0;
    padding: 0;
    width: 50%;
}
.production-button {
  align-self: center;
  margin-right: 8px;
}
.production-kindbutton {
  padding: 8px !important;
}
.production-status {
  width: 70px;
  height: 60px;
  border: 3px solid #409EFF;
  border-radius: 50%;
  color: #409EFF;
  text-align: center;
  line-height: 60px ;
  font-size: 20px;
  font-weight: 550;
  position: absolute;
  right: 20px;
}
.StorageRecord-abnormal {
  display: flex;
  justify-content: space-around;
  line-height: 3;
}
.StorageRecord-abnormal span {
  width: 25%;
  text-align: center;
}
.StorageRecording-message span {
  color: red;
}
.StorageRecord-title {
  color: #454649;
  font-size: 17px;
}
.deliveryStartTime {
  background: rgb(229, 246, 253);
}
.deliveryBackground {
  background: oldlace;
}
.el-collapse-item__wrap {
  background: rgb(229, 246, 253);
}
.el-collapse {
  border: 0;
  margin-left: 10px;
}
.el-collapse-item__header.is-active {
  background: rgb(229,246,253);
  color: #3a8ee6;
  font-size: 18px;
}
.el-collapse-item__header {
  background: rgb(229,246,253);
  color: #3a8ee6;
  font-size: 18px;
  font-weight: 550;
}
.el-collapse-item__content {
  margin-top: 10px;
  font-size: 15px;
}
#pdf-viewer #content {
  height: 350px!important;
  position: fixed;
  width: 100%;
  z-index: 1;
}
.StorageRecord-titles {
  display: inline-block;
  width: 25%;
  text-align: center;
}
/* ------- 自制折叠面板 -------- */
.arrow {
  display: block;
  width: 10px;
  height: 10px;
  margin-top: 13px;
  border-top: 1px solid #3a8ee6;
  border-right: 1px solid #3a8ee6;
  transform: rotate(45deg);
  /* transition: transform .3s; */
}
.fire-box {
  padding: 4px;
  padding-right: 8px;
  margin-right: 20px;
  display: inline-flex;
  align-items: center;
  color: #ea565b;
  border-radius: 4px;
  border: 1px solid rgba(245,108,108,.4);
  float: right;
}
.fire-icon {
  animation: blink .8s infinite;
}
@keyframes blink {
  0% { opacity: 1; }
  100% { opacity: 0; }
}
</style>
